package com.gopay.checkorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.tbank.ebank.pay.TBankMessage;
import com.gopay.common.domain.bank.tbank.ebank.query.res.TBankBodyRes;
import com.gopay.common.domain.bank.tbank.ebank.query.res.TBankOrderRes;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * 测试银行对单
 * 
 * @CheckOrderTBankImpl.java
 * @author yaobo
 * @2013-3-20 上午11:12:29 www.gopay.com.cn Inc.All rights reserved.
 */
public class CheckOrderTBankImpl implements BankOrderService {
    private final static Logger logger = LoggerFactory.getLogger("TBANK");

    @Resource(name = "bankClient")
    private BankInteractRemoteService bankClient;

    @Override
    public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
        CheckOrderResult checkOrderResult = new CheckOrderResult();
        checkOrderResult.setOrderId(bankOrder.getOrderId());

        TBankMessage base = new TBankMessage();
		base.setOrderId(bankOrder.getOrderId());
		base.setBankOrderId(bankOrder.getOutOrderId());
		base.setBank(BankConstants.BANK_LOGO_TBANK);
		base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
		base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));

        Result result = new Result();
        try {
            result = bankClient.query(base);
        } catch (Exception e) {
            logger.error("bankClient fail.", e);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
            checkOrderResult.setErrMsg("对账异常");
            return checkOrderResult;
        }

        if (result == null || !result.isSuccess() || result.getDefaultModel() == null) {
            logger.error("bankClient fail.");
            if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
            	BankCountDownLatch.failIncrease(bankOrder.getBankCode());
            	checkOrderResult.setCommunicateError(true);
			}
            logger.error(ToStringBuilder.reflectionToString(result, ToStringStyle.DEFAULT_STYLE));
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
            checkOrderResult.setErrMsg("系统返回对账结果为空");
            return checkOrderResult;
        }

        TBankOrderRes res = (TBankOrderRes) result.getDefaultModel();
        if (res == null) {
            // 查询订单为空
            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E5062+ " err:bis query is null.");
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
            checkOrderResult.setErrMsg("银行返回对账结果为空");
        }

        if (StringUtils.isNotBlank(res.getHeader().getErr())) {
            // 查询订单错误
            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + res.getHeader().getCode() + " err:"+ res.getHeader().getErr());
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
            checkOrderResult.setErrMsg(res.getHeader().getErr());
            return checkOrderResult;
        }
        TBankBodyRes orderRes = (TBankBodyRes) res.getOrders().get(0);
        checkOrderResult.setOrderId(orderRes.getOrderNo());
        checkOrderResult.setAmount(new BigDecimal(orderRes.getOrderAmount()));
        //成功处理
        if (StringUtils.equals("S0200", orderRes.getRetCd())) {
            checkOrderResult.setSuccess(true);
            InAccInfo accInfo = new InAccInfo();
            accInfo.setOrderId(bankOrder.getOrderId());
            accInfo.setAmount(new BigDecimal(orderRes.getOrderAmount()));
            accInfo.setRetCode("00");
            accInfo.setCardType(BankCardType.Unknown.toString());
            checkOrderResult.setAccInfo(accInfo);
        } else {
            // 银行订单状态为失败
        	checkOrderResult.setBankFailure(true);
            checkOrderResult.setErrMsg("银行订单未查到");
        }
        return checkOrderResult;
    }

	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
